// Supabase 配置
const SUPABASE_CONFIG = {
    // 请替换为您的 Supabase 项目 URL 和 API Key
    url: 'YOUR_SUPABASE_URL', // 例如: 'https://your-project.supabase.co'
    anonKey: 'YOUR_SUPABASE_ANON_KEY', // 您的匿名密钥
};

// 应用配置
const APP_CONFIG = {
    // 精油浓度配置 (占蜡的百分比)
    oilConcentration: {
        min: 3,  // 最小3%
        max: 10, // 最大10%
        default: 6 // 默认6%
    },
    
    // 利润率配置
    profitMargin: {
        min: 20,     // 最小利润率20%
        suggested: 50, // 建议利润率50%
        high: 100    // 高利润率100%
    },
    
    // 货币格式
    currency: {
        symbol: '¥',
        locale: 'zh-CN'
    },
    
    // 数据库表名
    tables: {
        products: 'candle_products',
        inventory: 'inventory',
        materials: 'materials',
        orders: 'orders'
    }
};

// 初始化 Supabase 客户端
let supabase = null;

// 初始化函数
function initializeSupabase() {
    if (SUPABASE_CONFIG.url === 'YOUR_SUPABASE_URL' || SUPABASE_CONFIG.anonKey === 'YOUR_SUPABASE_ANON_KEY') {
        console.warn('请在 config.js 中配置您的 Supabase 凭据');
        return false;
    }
    
    try {
        supabase = window.supabase.createClient(SUPABASE_CONFIG.url, SUPABASE_CONFIG.anonKey);
        console.log('Supabase 客户端初始化成功');
        return true;
    } catch (error) {
        console.error('Supabase 初始化失败:', error);
        return false;
    }
}

// 格式化价格
function formatPrice(price) {
    return new Intl.NumberFormat(APP_CONFIG.currency.locale, {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2
    }).format(price);
}

// 计算利润率
function calculateProfitMargin(cost, sellingPrice) {
    if (cost === 0) return 0;
    return ((sellingPrice - cost) / cost * 100).toFixed(1);
}

// 生成唯一ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#48bb78' : type === 'error' ? '#f56565' : '#667eea'};
        color: white;
        padding: 16px 20px;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 300px;
        word-wrap: break-word;
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 数据管理器 - 云端优先，本地备用
const DataManager = {
    // 缓存数据
    cache: {
        essentialOils: null,
        containers: null,
        packagingTypes: null,
        waxTypes: null,
        effectCategories: null,
        lastUpdate: null
    },

    // 获取精油数据
    async getEssentialOils() {
        if (this.cache.essentialOils && this.isCacheValid()) {
            return this.cache.essentialOils;
        }

        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('essential_oils')
                    .select('*')
                    .order('name');
                
                if (error) throw error;
                
                if (data && data.length > 0) {
                    this.cache.essentialOils = data;
                    this.updateCacheTimestamp();
                    this.saveToLocalStorage('essential_oils', data);
                    return data;
                }
            }
        } catch (error) {
            console.warn('云端获取精油数据失败，使用本地数据:', error);
        }
        
        // 备用：本地存储或默认数据
        const localData = this.getFromLocalStorage('essential_oils');
        if (localData) {
            this.cache.essentialOils = localData;
            return localData;
        }
        
        // 最后备用：使用data.js中的默认数据
        if (window.MYSTICAL_DATA && window.MYSTICAL_DATA.essentialOils) {
            this.cache.essentialOils = window.MYSTICAL_DATA.essentialOils;
            return window.MYSTICAL_DATA.essentialOils;
        }
        
        return [];
    },

    // 获取容器数据
    async getContainers() {
        if (this.cache.containers && this.isCacheValid()) {
            return this.cache.containers;
        }

        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('containers')
                    .select('*')
                    .order('name');
                
                if (error) throw error;
                
                if (data && data.length > 0) {
                    this.cache.containers = data;
                    this.updateCacheTimestamp();
                    this.saveToLocalStorage('containers', data);
                    return data;
                }
            }
        } catch (error) {
            console.warn('云端获取容器数据失败，使用本地数据:', error);
        }
        
        const localData = this.getFromLocalStorage('containers');
        if (localData) {
            this.cache.containers = localData;
            return localData;
        }
        
        if (window.MYSTICAL_DATA && window.MYSTICAL_DATA.containers) {
            this.cache.containers = window.MYSTICAL_DATA.containers;
            return window.MYSTICAL_DATA.containers;
        }
        
        return [];
    },

    // 获取包装类型数据
    async getPackagingTypes() {
        if (this.cache.packagingTypes && this.isCacheValid()) {
            return this.cache.packagingTypes;
        }

        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('packaging_types')
                    .select('*')
                    .order('name');
                
                if (error) throw error;
                
                if (data && data.length > 0) {
                    this.cache.packagingTypes = data;
                    this.updateCacheTimestamp();
                    this.saveToLocalStorage('packaging_types', data);
                    return data;
                }
            }
        } catch (error) {
            console.warn('云端获取包装数据失败，使用本地数据:', error);
        }
        
        const localData = this.getFromLocalStorage('packaging_types');
        if (localData) {
            this.cache.packagingTypes = localData;
            return localData;
        }
        
        if (window.MYSTICAL_DATA && window.MYSTICAL_DATA.packaging) {
            this.cache.packagingTypes = window.MYSTICAL_DATA.packaging;
            return window.MYSTICAL_DATA.packaging;
        }
        
        return [];
    },

    // 获取蜡材数据
    async getWaxTypes() {
        if (this.cache.waxTypes && this.isCacheValid()) {
            return this.cache.waxTypes;
        }

        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('wax_types')
                    .select('*')
                    .order('name');
                
                if (error) throw error;
                
                if (data && data.length > 0) {
                    this.cache.waxTypes = data;
                    this.updateCacheTimestamp();
                    this.saveToLocalStorage('wax_types', data);
                    return data;
                }
            }
        } catch (error) {
            console.warn('云端获取蜡材数据失败，使用本地数据:', error);
        }
        
        const localData = this.getFromLocalStorage('wax_types');
        if (localData) {
            this.cache.waxTypes = localData;
            return localData;
        }
        
        if (window.MYSTICAL_DATA && window.MYSTICAL_DATA.waxTypes) {
            this.cache.waxTypes = window.MYSTICAL_DATA.waxTypes;
            return window.MYSTICAL_DATA.waxTypes;
        }
        
        return [];
    },

    // 获取功效分类数据
    async getEffectCategories() {
        if (this.cache.effectCategories && this.isCacheValid()) {
            return this.cache.effectCategories;
        }

        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('effect_categories')
                    .select('*')
                    .order('name');
                
                if (error) throw error;
                
                if (data && data.length > 0) {
                    this.cache.effectCategories = data;
                    this.updateCacheTimestamp();
                    this.saveToLocalStorage('effect_categories', data);
                    return data;
                }
            }
        } catch (error) {
            console.warn('云端获取功效数据失败，使用本地数据:', error);
        }
        
        const localData = this.getFromLocalStorage('effect_categories');
        if (localData) {
            this.cache.effectCategories = localData;
            return localData;
        }
        
        if (window.MYSTICAL_DATA && window.MYSTICAL_DATA.effects) {
            this.cache.effectCategories = window.MYSTICAL_DATA.effects;
            return window.MYSTICAL_DATA.effects;
        }
        
        return [];
    },

    // 缓存管理
    isCacheValid() {
        if (!this.cache.lastUpdate) return false;
        const now = new Date().getTime();
        const cacheAge = now - this.cache.lastUpdate;
        return cacheAge < (5 * 60 * 1000); // 5分钟缓存
    },

    updateCacheTimestamp() {
        this.cache.lastUpdate = new Date().getTime();
    },

    // 本地存储管理
    saveToLocalStorage(key, data) {
        try {
            localStorage.setItem(`candle_data_${key}`, JSON.stringify({
                data: data,
                timestamp: new Date().getTime()
            }));
        } catch (error) {
            console.warn('保存到本地存储失败:', error);
        }
    },

    getFromLocalStorage(key) {
        try {
            const stored = localStorage.getItem(`candle_data_${key}`);
            if (stored) {
                const parsed = JSON.parse(stored);
                return parsed.data;
            }
        } catch (error) {
            console.warn('从本地存储读取失败:', error);
        }
        return null;
    },

    // 清除缓存
    clearCache() {
        this.cache = {
            essentialOils: null,
            containers: null,
            packagingTypes: null,
            waxTypes: null,
            effectCategories: null,
            lastUpdate: null
        };
    }
};

// 产品数据库管理器 - 处理产品库存
const DatabaseManager = {
    // 保存产品到库存
    async saveProduct(productData) {
        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('products')
                    .insert([productData])
                    .select();
                    
                if (error) throw error;
                showNotification('产品已保存到云端数据库', 'success');
                return data[0];
            }
        } catch (error) {
            console.warn('云端保存失败，使用本地存储:', error);
        }
        
        // 备用：本地存储
        const products = JSON.parse(localStorage.getItem('candle_products') || '[]');
        productData.id = productData.id || generateId();
        products.push(productData);
        localStorage.setItem('candle_products', JSON.stringify(products));
        showNotification('产品已保存到本地存储', 'info');
        return productData;
    },
    
    // 获取产品列表
    async getProducts() {
        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('products')
                    .select('*')
                    .order('created_at', { ascending: false });
                    
                if (error) throw error;
                return data || [];
            }
        } catch (error) {
            console.warn('云端获取失败，使用本地存储:', error);
        }
        
        // 备用：本地存储
        return JSON.parse(localStorage.getItem('candle_products') || '[]');
    },
    
    // 更新产品
    async updateProduct(id, updates) {
        try {
            if (supabase) {
                const { data, error } = await supabase
                    .from('products')
                    .update(updates)
                    .eq('id', id)
                    .select();
                    
                if (error) throw error;
                showNotification('产品已更新', 'success');
                return data[0];
            }
        } catch (error) {
            console.warn('云端更新失败，使用本地存储:', error);
        }
        
        // 备用：本地存储
        const products = JSON.parse(localStorage.getItem('candle_products') || '[]');
        const index = products.findIndex(p => p.id === id);
        if (index !== -1) {
            products[index] = { ...products[index], ...updates };
            localStorage.setItem('candle_products', JSON.stringify(products));
            showNotification('产品已更新', 'info');
            return products[index];
        }
        return null;
    },
    
    // 删除产品
    async deleteProduct(id) {
        try {
            if (supabase) {
                const { error } = await supabase
                    .from('products')
                    .delete()
                    .eq('id', id);
                    
                if (error) throw error;
                showNotification('产品已删除', 'success');
                return true;
            }
        } catch (error) {
            console.warn('云端删除失败，使用本地存储:', error);
        }
        
        // 备用：本地存储
        const products = JSON.parse(localStorage.getItem('candle_products') || '[]');
        const filteredProducts = products.filter(p => p.id !== id);
        localStorage.setItem('candle_products', JSON.stringify(filteredProducts));
        showNotification('产品已删除', 'info');
        return true;
    }
};

// 导出配置和函数
window.APP_CONFIG = APP_CONFIG;
window.SUPABASE_CONFIG = SUPABASE_CONFIG;
window.initializeSupabase = initializeSupabase;
window.formatPrice = formatPrice;
window.calculateProfitMargin = calculateProfitMargin;
window.generateId = generateId;
window.showNotification = showNotification;
window.DataManager = DataManager;
window.DatabaseManager = DatabaseManager;